<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <div>
          <a-form size="small" layout="inline" :model="pageData">
            <a-form-item label="角色名称">
              <a-input :style="{ width: '200px' }" v-model="pageData.searchParams.roleName" class="bacClass"
                placeholder="" @press-enter="huiche"></a-input>
              <!-- <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" :loading="loading" :allowClear="true"
                            :filter-option="false" allow-search v-model="pageData.searchParams.roleName" @search="handleSearch"
                            @focus="focusSel">
                            <a-option v-for="item in pageData.searchParams.roleNameList" :value="item['roleName']">
                                {{ item['roleName'] }}
                            </a-option>
                        </a-select> -->
            </a-form-item>
          </a-form>
        </div>

        <div class="my-tool-bar">
          <ToolBar @add="addHandler" :style="{ marginRight: '20px' }" @select="selecth" @open="headerShow = true"
            @del="deleteHandler" @close="headerShow = false" :items="pageData.btnList"></ToolBar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height: 100%; width: 100%; z-index: 999">
        <encapsulation-agrid style="height: 100%" ref="gridOption" :configaggrid="configTable1"></encapsulation-agrid>
        <!-- <AgGridVuesCopys
          :rowHeight="33"
          :headerHeight="33"
          :suppressCopyRowsToClipboard="true"
          rowSelection="multiple"
          @grid-ready="gridReady"
          style="height: 100%"
          :defaultColDef="defaultColDef"
          class="ag-theme-alpine"
          :rowData="table.dataList"
          :columnDefs="tc"
          :localeText="localeText1"
        ></AgGridVuesCopys> -->
      </a-spin>
      <!-- </a-tab-pane>
            </a-tabs> -->
    </template>

    <!-- <paginationCopys
      :page-size="pagination.pageSize"
      :page-size-options="optionsList"
      :current="pagination.page"
      :total="pagination.total"
      show-total
      show-jumper
      show-page-size
      @change="PageSize2"
      @page-size-change="change12"
      style="justify-content: center"
    /> -->

    <a-drawer ok-text="保存" cancel-text="关闭" :style="{ zIndex: '999' }" :width="400" popup-container=".arco-tabs-content"
      :visible="pageData.showSide" @cancel="pageData.showSide = false" :mask-closable="false" @ok="sideOk"
      :ok-loading="saveLoading">
      <template #title> {{ pageData.sideTitle }}</template>
      <a-form ref="formRef" layout="horizontal" :model="dataForm" field="roleCode">
        <a-form-item label-col-flex="80px" label="角色编号" :rules="[
          { required: true, message: '编号必填' },
          { match: /^[a-zA-Z0-9]{1,}$/g, message: '编号必须是数字和字母' },
        ]" :validate-trigger="['change', 'blur']">
          <a-input class="bacClass" @blur="dataForm.roleCode = dataForm.roleCode.toUpperCase()"
            v-model="dataForm.roleCode" placeholder=""></a-input>
        </a-form-item>
        <a-form-item label-col-flex="80px" label="角色名" field="roleName" :rules="[{ required: true, message: '角色名必填' }]"
          :validate-trigger="['change', 'blur']">
          <a-input class="bacClass" v-model="dataForm.roleName" placeholder=""></a-input>
        </a-form-item>
        <a-form-item label-col-flex="80px" label="备注" field="remark">
          <a-textarea class="bacClass" placeholder="" v-model="dataForm.remark" :max-length="400" allow-clear
            show-word-limit />
        </a-form-item>
      </a-form>
    </a-drawer>

    <a-modal @ok="rok" @cancel="modalCancel" :visible="setRoleData.show" title="角色权限设置" :ok-loading="confirmLoading">
      <a-spin :loading="confirmLoading" tip="加载中" dot style="height: 100%; width: 100%; z-index: 999"
        v-show="setRoleData.show">
        <!-- <a-scrollbar style="height: 500px; overflow: auto">
          <a-tree v-model:expanded-keys="zk" default-expand-all ref="roletree" :data="data1"
            v-model:checked-keys="rowlist" checkable show-line>
          </a-tree>
        </a-scrollbar> -->
        <el-tree-v2 :data="dataList" :props="{
          value: 'id',
          label: 'name',
          children: 'children',
        }" show-checkbox :height="550" ref="treeV2"  :check-on-click-node="true"
          :default-checked-keys="defaultCheckedKeys"   :default-expanded-keys="['1']" highlight-current node-key="id"/>
      </a-spin>
    </a-modal>
  </pageTabelLayout>
</template>
<script lang="ts">
import { reactive, toRefs, onMounted, ref } from 'vue'

import {
  useRowKey,
  useTable,
  useRowSelection,
  usePagination,
  useTableColumn,
} from '@/hooks/table'
import ToolBar from '@/components/Toolbar.vue'
import { del, get, post, put } from '@/api/http'
import { FormInstance, Message, Modal, TreeInstance } from '@arco-design/web-vue'
import { column } from 'element-plus/es/components/table-v2/src/common'

import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
import usePermission from '@/store/modules/permission'
interface Role {
  id: number | string
  roleName: string
  roleCode: string
  remark: string
  deleteState: boolean
}

export default {
  name: 'Roles',
  components: {
    ToolBar,
  },

  setup() {
    const optionsList: any = ref(pagingList)
    const confirmLoading = ref<boolean>(false) //编辑权限弹窗的确定按钮加载层

    function PageSize2(val: any) {
      pagination.page = val
      doRefresh()
    }
    function change12(val: any) {
      pagination.pageSize = val
      doRefresh()
    }

    const selecth = () => {
      pagination.page = 1
      doRefresh()
    }

    const dataList = ref<any[]>([])

    onMounted(() => {
      doRefresh()
      get({
        url: 'admin/acl/permission/indexAllPermission',
      }).then(({ code, data }) => {
        if (code === 200) {
          dataList.value = data.children
        } else {
          Message.error('获取菜单失败！')
        }
      })
    })

    const headerShow = ref<boolean>(true)
    const doRefresh = () => {
      // if (pageData.pageLoading) return
      // pageData.pageLoading = true
      // get({
      //   url: 'admin/acl/role/index',
      //   data: {
      //     page: pagination.page,
      //     limit: pagination.pageSize,
      //     roleName: pageData.searchParams.roleName,
      //   },
      // })
      //   .then((res) => {
      //     table.handleSuccess(res.data.items)
      //     gridOption.value.setRowData(res.data.items)
      //     pagination.setTotalSize(res.data.total)
      //   })
      //   .finally(() => {
      //     pageData.pageLoading = false
      //   })
      try {
        gridOption.value.setQuery({
          roleName: pageData.searchParams.roleName,
        })
      } catch (error) {
        console.log(error);

      } finally {
        // pageData.pageLoading = false
      }
    }
    const pageData = reactive<{
      searchParams: {
        roleName: string
        roleNameList: []
      }
      showSide: boolean
      sideTitle: string
      sideLoding: boolean
      pageLoading: boolean
      btnList: any[]
    }>({
      showSide: false,
      sideTitle: '新增菜单',
      searchParams: {
        roleName: '',
        roleNameList: [],
      },
      sideLoding: false,
      pageLoading: false,
      btnList: [],
    })
    const { selectedRowKeys, onSelectionChange } = useRowSelection()
    const pagination = usePagination(doRefresh)
    const table = useTable()
    const rowKey = useRowKey('id')
    const tableColumns = useTableColumn([
      {
        title: '角色编号',
        key: 'roleCode',
        dataIndex: 'roleCode',
        width: 100,
      },
      {
        title: '角色名',
        key: 'roleName',
        dataIndex: 'roleName',
      },
      {
        title: '备注',
        key: 'remark',
        dataIndex: 'remark',
      },
      {
        title: '修改时间',
        dataIndex: 'gmtModified',
        key: 'gmtModified',
      },
      {
        title: '操作',
        key: 'id',
        fixed: 'right',
        slotName: 'action',
        width: 300,
      },
    ])
    // const tableData = reactive<{ selectedRowKeys: any[], table: any, pagination: any, rowKey: any, rowSelection: any, column: any, rowData: any[] }>({
    //     rowData: [],
    //     table: useTable(),
    //     pagination: usePagination(doRefresh),
    //     rowKey: useRowKey('id'),
    //     rowSelection: useRowSelection(),
    //     selectedRowKeys: [],
    //     column: useTableColumn([{
    //         title: '角色编号',
    //         key: 'roleCode',
    //         dataIndex: 'roleCode',
    //         width: 100
    //     }, {
    //         title: '角色名',
    //         key: 'roleName',
    //         dataIndex: 'roleName'

    //     }, {
    //         title: '备注',
    //         key: 'remark',
    //         dataIndex: 'remark'
    //     }, {
    //         title: '修改时间',
    //         dataIndex: 'gmtModified',
    //         key: 'gmtModified'
    //     }, {
    //         title: '操作',
    //         key: 'id',
    //         fixed: 'right',
    //         slotName: 'action',
    //         width: 300
    //     }])
    // })
    const dataForm = reactive<Role>({
      id: '',
      remark: '',
      roleCode: '',
      roleName: '',
      deleteState: false,
    })
    const addHandler = () => {
      Object.keys(dataForm).forEach((o) => (dataForm[o] = undefined))
      pageData.sideTitle = '新增角色'
      pageData.showSide = true
    }

    const deleteHandler = () => {
      if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      }
      Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        onOk() {
          del({
            // url: "admin/acl/role/batchRemove/" + tableData.selectedRowKeys.join(','),
            url:
              'admin/acl/role/batchRemove/' +
              gridOption.value
                .getSelectedRows()
                .map((o: any) => {
                  return o.id
                })
                .join(','),
          }).then(({ code, data }: any) => {
            if (code === 200) {
              Message.success({
                content: '删除成功',
                duration: 5000,
              })
              // tableData.pagination.page = 1
              doRefresh()
            } else {
              Message.error({
                content: '删除失败',
                duration: 5000,
              })
            }
          })
        },
      })
    }
    const formRef = ref<FormInstance>()
    const sideOk = () => {
      saveLoading.value = true
      formRef.value?.validate().then(async (err) => {
        if (!err) {
          pageData.sideLoding = true
          if (pageData.sideTitle === '新增角色') {
            try {
              const res = await post({
                url: 'admin/acl/role/save',
                data: {
                  deleteState: false,
                  roleCode: dataForm.roleCode,
                  roleName: dataForm.roleName,
                  remark: dataForm.remark,
                },
              })
              if (res.code === 200) {
                Message.success('新增成功')
                pageData.showSide = false
                doRefresh()
              } else {
                Message.error(res['message'] || '新增失败')
              }
            } catch (error) {
              console.log(error)
            } finally {
              saveLoading.value = false
            }
          } else {
            try {
              const res = await put({
                url: 'admin/acl/role/update',
                data: {
                  deleteState: false,
                  roleCode: dataForm.roleCode,
                  roleName: dataForm.roleName,
                  id: dataForm.id,
                  remark: dataForm.remark,
                },
              })
              if (res.code === 200) {
                Message.success('修改成功')
                pageData.showSide = false
                doRefresh()
              } else {
                Message.error(res['message'] || '修改失败')
              }
            } catch (error) {
              console.log(error)
            } finally {
              saveLoading.value = false
            }
          }
        }
      })
    }

    const editHandler = (record: Role) => {
      Object.keys(dataForm).forEach((o) => (dataForm[o] = record[o]))
      pageData.sideTitle = '修改角色'
      pageData.showSide = true
    }

    const roletree: any = ref<TreeInstance>()
    const zk = ref<any>([])
    const rowlist = ref<any>([])
    const defaultCheckedKeys = ref([])
    
    let roid = ''


    const editRolesHandler = (record: Role) => {
      get({
        url: 'admin/acl/permission/toAssign/' + record.id,
      }).then(({ code, data }) => {
        if (code === 200) {
          rowlist.value = []
          defaultCheckedKeys.value = []

          data.children.forEach(function (o: any) {
            zk.value.push(o.id)
            if (Array.isArray(o.children) && o.children.length > 0) {
              o.children.forEach((o1: any) => {
                zk.value.push(o1.id)
                if (Array.isArray(o1.children) && o1.children.length > 0) {
                  o1.children.forEach((o2: any) => {
                    if (Array.isArray(o2.children) && o2.children.length > 0) {
                      o2.children.forEach((o3: any) => {
                        if (Array.isArray(o3.children) && o3.children.length > 0) {
                          o3.children.forEach((o4: any) => {
                            if (Array.isArray(o4.children) && o4.children.length > 0) {
                              o4.children.forEach((o5: any) => {
                                if (o5.select) rowlist.value.push(o5.id)
                              })
                            } else {
                              if (o4.select) rowlist.value.push(o4.id)
                            }
                          })
                        } else {
                          if (o3.select) rowlist.value.push(o3.id)
                        }
                      })
                    } else {
                      if (o2.select) rowlist.value.push(o2.id)
                    }
                  })
                } else {
                  if (o1.select) rowlist.value.push(o1.id)
                }
              })
            } else {
              if (o.select) rowlist.value.push(o.id)
            }
          })
          defaultCheckedKeys.value = findCheckedLeafNodeIds(dataList.value)
          console.log(findCheckedLeafNodeIds(dataList.value))
          treeV2.value?.setCheckedKeys(defaultCheckedKeys.value)
          roid = record.id + ''
          fuid.value = data.children[0].id
          setRoleData.show = true
        } else {
          Message.error('获取角色权限失败')
        }
      })
    }

    function findCheckedLeafNodeIds(treeData) {
      const checkedLeafIds = [];

      // 定义递归函数  
      function findLeafNodes(node) {
        // 如果节点是叶子节点（即 children 属性不存在或为空数组），并且其ID在defaultCheckedKeys中  
        if (!node.children || node.children.length === 0 && rowlist.value.includes(node.id)) {
          checkedLeafIds.push(node.id);
        } else {
          // 否则，递归处理其子节点  
          if (node.children) {
            node.children.forEach(child => {
              findLeafNodes(child);
            });
          }
        }
      }

      // 遍历树形数据的每个根节点，并调用递归函数  
      treeData.forEach(rootNode => {
        findLeafNodes(rootNode);
      });

      // 返回符合条件的叶子节点的ID数组  
      return checkedLeafIds;
    }


    const treeV2 = ref('')
    const rok = async () => {
      // confirmLoading.value = true
      // pageData.pageLoading = true

      try {
        const res = await post({
          url: '/admin/acl/permission/doAssign?roleId=' + roid,
          // data: rowlist.value,
          data: [...treeV2.value?.getHalfCheckedKeys(), ...treeV2.value?.getCheckedKeys()],
        })
        if (res.code === 200) {
          Message.success('设置成功')
          setRoleData.show = false
        } else {
          Message.error(res.message)
        }
      } catch (error) {
        console.log(error)
      } finally {
        confirmLoading.value = false
        pageData.pageLoading = false
      }
    }

    //下拉框得到焦点
    const focusSel = () => {
      selRoleName({
        page: 1,
        limit: 30,
      })
    }
    //下拉数据
    const options = ref<any>(pageData.searchParams.roleNameList)
    const loading = ref(false)
    const handleSearch = (value: any) => {
      if (value) {
        const ob = {
          page: 1,
          limit: 30,
          roleName: value,
        }
        loading.value = true
        // 角色下拉框查询
        selRoleName(ob)
        options.value = pageData.searchParams.roleNameList
        loading.value = false
      } else {
        options.value = []
      }
    }

    //角色下拉框查询
    function selRoleName(val: any) {
      get({
        url: 'admin/acl/role/index',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          pageData.searchParams.roleNameList = data.items
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }
    // 设置权限的弹窗
    const setRoleData = reactive({
      show: false,
    })
    const handleChange = (_data: any) => {
      table.handleSuccess(_data)
    }
    const gridOption = ref()
    // const gridReady = (params: any) => {
    //   gridOption.value = params.api
    //   // gridOption.value.sizeColumnsToFit();
    // }

    let tc: any[] = tableColumns.map((o: any) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
        tooltipField: o.key,
      }
      obj['width'] = 350

      if (o.slotName === 'action') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['lockPosition'] = 'right'
        obj['width'] = 175
        obj['cellRenderer'] = {
          template: `<a-space><a-tag  class="tagCss" @click="a" v-if="f">修改</a-tag>
        <a-tag @click="b" class="tagCss" v-if="g">编辑权限</a-tag></a-space>
        `,
          setup(props: any) {
            const a = () => {
              editHandler(props.params.data)
            }
            const b = () => {
              editRolesHandler(props.params.data)
            }
            let f = permissionStore.hasPermisson('jsgl.xg')
            let g = permissionStore.hasPermisson('jsgl.bjqx')
            return {
              b,
              a,
              f,
              g,
            }
          },
        }
      }

      return obj
    })

    let a = [
      {
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
      },
    ]
    tc = a.concat(tc)
    const defaultColDef = {
      sortable: true,
      resizable: true,
      filter: true,
      // flex: 1
    }
    let configTable1 = ref({
      url: 'admin/acl/role/index', //接口路径
      queryData: {
        //接口参数
      },
      isGet: true,//是否是get请求
      isLimit: true,//后端分页接收limit而非size
      paginationShow: true, //分页是否显示
      invokeiIterface: true, //是否调用接
      rowMultiSelectWithClick: false, //点击行是否多选
      column: tc,
      fileName: 'roles'
    })
    const localeText1: any = ref(localeText)
    const huiche = () => {
      doRefresh()
    }
    //设置权限
    // ['查询', '新增', '删除', '导出', '导入']
    const permissionStore = usePermission()

    if (permissionStore.hasPermisson('jsgl.cx')) {
      pageData.btnList.push('查询')
    }
    if (permissionStore.hasPermisson('jsgl.xz')) {
      pageData.btnList.push('新增')
    }
    if (permissionStore.hasPermisson('jsgl.sc')) {
      pageData.btnList.push('删除')
    }

    const fuid = ref('')
    const saveLoading = ref(false)
    const modalCancel = () => {
      if (confirmLoading.value) return
      setRoleData.show = false
    }
    return {
      fuid,
      huiche,
      table,
      pagination,
      pageData,
      change12,
      PageSize2,
      selecth,
      localeText1,
      defaultColDef,
      tc,
      rowlist,
      treeV2,
      zk,
      rok,
      roletree,
      dataList,
      defaultCheckedKeys,
      loading,
      setRoleData,
      editRolesHandler,
      editHandler,
      sideOk,
      dataForm,
      optionsList,
      formRef,
      addHandler,
      // ...toRefs(pageData),
      // ...toRefs(tableData),
      doRefresh,
      headerShow,
      handleSearch,
      focusSel,
      // PageSize,
      // change1,
      deleteHandler,
      handleChange,
      // gridReady,
      saveLoading,
      confirmLoading,
      modalCancel,
      configTable1,
      gridOption
    }
  },
}
</script>
<style scoped lang="less">
.my-container {
  height: 100%;
  min-height: 500px;
  max-height: 90%;
  width: 100%;
  max-height: 100%;

  &>.my-header {
    width: 100%;
    padding: 10px;
    padding-top: 0;
    background-color: white;

    min-height: 10%;

    &>.my-tool-bar {
      text-align: right;
    }
  }

  &>.my-body {
    width: 100%;
    padding: 10px;
    background-color: white;
    height: 85%;
    max-height: calc(85% + 40px);
  }

  &>.split-bar {
    height: 10px;
    width: 100%;
  }
}

:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}
</style>
